package com.hht.toolanduilibs.widget

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.text.format.DateFormat
import android.util.AttributeSet
import android.widget.RelativeLayout
import androidx.annotation.RequiresApi
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*


/**
 * Author:chen'hu
 * Time:2023/8/4 15:55
 * Description:自定义时钟基类
 */
abstract class BaseClockView(context: Context, attrs: AttributeSet? = null) :
    RelativeLayout(context, attrs) {
    companion object {
        private const val ACTION_DATE_FORMAT_CHANGE = "hht.settings.dateformat.change"
        private const val DATE_FORMAT_TAG = "dateFormat"
    }

    private var dateFormat: String? = null
    private val mDate = Date()
    private var mReceiver: ClockReceiver? = null
    var timeHandler = Handler(Looper.getMainLooper())

    @RequiresApi(Build.VERSION_CODES.CUPCAKE)
    var mTimeUpdateRunnable = Runnable {
        mDate.time = System.currentTimeMillis()
        val simpleWeekFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        val simpleDateFormat = SimpleDateFormat(dateFormat, Locale.getDefault())
        val simpleTimeFormat = SimpleDateFormat(getTimeFormat(), Locale.getDefault())
        updateTime(simpleWeekFormat, simpleTimeFormat, mDate)
    }

    init {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) {
            getDateFormat()
        }
    }

    @RequiresApi(Build.VERSION_CODES.CUPCAKE)
    fun updateCurrentClock() {
        removeUpdateCurrentClockPost()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) {
            getDateFormat()
        }
        timeHandler.post(mTimeUpdateRunnable)
    }

    /**
     * 注册时间变化广播
     */
    private fun registerBroadcastReceiver() {
        if (mReceiver == null) {
            mReceiver = ClockReceiver()
            val filter = IntentFilter()
            filter.addAction(ACTION_DATE_FORMAT_CHANGE)
            filter.addAction(Intent.ACTION_TIME_TICK)
            filter.addAction(Intent.ACTION_TIME_CHANGED)
            filter.addAction(Intent.ACTION_TIMEZONE_CHANGED)
            context.registerReceiver(mReceiver, filter)
        }
    }

    /**
     * 注册时间变化广播接受者
     */
    private inner class ClockReceiver : BroadcastReceiver() {
        @RequiresApi(Build.VERSION_CODES.CUPCAKE)
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            if (ACTION_DATE_FORMAT_CHANGE == action) {
                dateFormat = intent.getStringExtra(DATE_FORMAT_TAG)
            } else if (Intent.ACTION_TIME_TICK == action || Intent.ACTION_TIME_CHANGED == action || Intent.ACTION_TIMEZONE_CHANGED == action) { //系统每分钟会发出该广播
                timeHandler.post(mTimeUpdateRunnable)
            }
        }
    }

    @RequiresApi(Build.VERSION_CODES.CUPCAKE)
    open fun removeUpdateCurrentClockPost() {
        timeHandler.removeCallbacks(mTimeUpdateRunnable)
    }

    /**
     * 更新时间
     * @param dateFormat  2022-11-18
     * @param timeFormat  03:47 PM
     * @param date  系统时间
     */
    open fun updateTime(dateFormat: SimpleDateFormat, timeFormat: SimpleDateFormat, date: Date?) {
        val currentTime = timeFormat.format(mDate)
        val pTime = dateFormat.format(date)
        val currentYear = pTime.substring(0, 4)
        val currentMonth = pTime.substring(5, 7)
        val currentDate = pTime.substring(8)
        val c = Calendar.getInstance()
        try {
            c.time = dateFormat.parse(pTime)
        } catch (e: ParseException) {
            e.printStackTrace()
        }
        // "updateTime: $pTime  $currentTime".showLog(1)
        updateTime(
            currentTime, currentYear, currentMonth, currentDate,
            c[Calendar.DAY_OF_WEEK]
        )
    }


    /**
     * 更新时间
     * @param currentTime   example 03:47 PM
     * @param currentYear   example 2023
     * @param currentMonth  example 8
     * @param currentDay    example 4
     * @param weekNumber    example 5
     */
    protected abstract fun updateTime(
        currentTime: String?,
        currentYear: String?,
        currentMonth: String?,
        currentDay: String?,
        weekNumber: Int,
    )

    /**
     * 获取时间格式
     * @return
     */
    @RequiresApi(Build.VERSION_CODES.CUPCAKE)
    private fun getTimeFormat(): String? {
        return if (DateFormat.is24HourFormat(context)) {
            "HH:mm "
        } else {
            "hh:mm aa"
        }
    }

    //获取日期格式
    @RequiresApi(Build.VERSION_CODES.CUPCAKE)
    private fun getDateFormat() {
        val dateFormatString = DateFormat.getDateFormat(context).format(Date(2017, 7, 31))
        val format = Settings.System.getString(context.contentResolver, Settings.System.DATE_FORMAT)
        val split = dateFormatString.split("/").toTypedArray()
        dateFormat = if (format != null) {
            if (format.contains("MM-dd")) {
                "MM-dd"
            } else if (format.contains("dd-MM")) {
                "dd-MM"
            } else {
                "MM-dd"
            }
        } else if (dateFormatString.isEmpty()) {
            if (split[0].contains("8")) {
                "MM-dd"
            } else {
                "dd-MM"
            }
        } else {
            "MM-dd"
        }
    }

    private fun unRegisterBroadcastReceiver() {
        try {
            if (mReceiver != null) {
                context.unregisterReceiver(mReceiver)
                mReceiver = null
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        registerBroadcastReceiver()
    }

    override fun onDetachedFromWindow() {
        unRegisterBroadcastReceiver()
        super.onDetachedFromWindow()
    }
}